var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
require('./utils/db') //导入数据库
// const cors=require('cors')
//导入express-jwt来完成验证
const {expressjwt}=require('express-jwt')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var songRouter=require('./routes/song')
var uploadRouter=require('./routes/upload')


var app = express();

/* 
  跨域的中间件处理函数
*/
const allowCross=(req,res,next)=>{
  res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:8888') //允许的域，白名单设置
  res.setHeader('Access-Control-Allow-Headers','X-Requested-With,Origin,Content-Type,Accept,Authorization')//除了9请求头之外的请求头
  res.setHeader('Access-Control-Allow-Methods','PUT,DELETE,OPTIONS') //允许的请求方式
  next()
}


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//设置跨域中间件
// app.use(cors())
//设置跨域的自定义中间件
app.use(allowCross)

//鉴权要在路由请求之前
app.use(expressjwt({
  secret:'gileskey',//密钥
  algorithms:['HS256']//jwt的加密算法

}).unless({path:['/users/login',/^\/images/]})) //unless将不需要token就能访问的页面可以放在其中
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/song',songRouter)
app.use('/upload',uploadRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
module.exports = app;
